Many operating systems allow applications, or computer programs, to be divided into multiple tasks that can execute in parallel. Multiple threads are typically allowed in a single process. Accordingly, a thread, which may be described as an execution path through a computer program and a kernel of an operating system, results when the computer program breaks into two or more concurrently executing tasks.
In multiprocessor computers, different threads of a multithreaded application may be concurrently executed on different processors. The multiple threads within an application can share resources (e.g., a shared variable, a file, or a device). Because threads execute at the same time, if more than one thread writes to the same data item, the data item may be corrupted. To avoid such scenarios, in multithreaded applications, locks may be used to block a shared resource from concurrent access by different threads that would allow one thread to make changes to the resource in a way that would interfere with the other thread.
When a thread acquires a lock, it becomes an owner of the lock and blocks other running threads from accessing the resources until it releases the lock. The lock may be, for example, a spin lock, where the waiting threads wait in a loop, or “spin,” while repeatedly checking whether the lock has been released by its owner.
Each thread executes in its context. The context of a thread can be defined as a set of values in hardware registers, stacks and other storage areas of the thread and an operating environment that the values define. Typically, when a processor switches from executing one thread to another, thread context switch occurs. For example, the context switch may occur when a thread waiting for a resource goes to sleep. Context switching consumes processor and operating system resources.